<template>
  <!-- 技术对比 -->
  <div>
    <!-- 搜索 -->
    <v-layout>
      <v-flex class="vflex" xs12>
        <v-card class="vcard">
          <v-card-title class="vcard-title"></v-card-title>
          <v-flex class="vflex" xs12>
            <div style="margin: 10px 20px;">
              <el-autocomplete
                class="search-bar"
                v-model="searchText"
                :fetch-suggestions="querySearchAsync"
                :placeholder="$t('assessment.InputKeywords')"
                :trigger-on-focus="false"
                @select="handleSelect"
                @keyup.enter.native="search"
              ></el-autocomplete>
              <ul class="search-history">
                <li
                  v-for="(item, index) in cityOptions"
                  :key="index"
                  @click="searchHistory(item)"
                  :class="{ active: item === activeItem }"
                >
                  {{ item }}
                </li>
              </ul>
            </div>
          </v-flex>
        </v-card>
      </v-flex>
    </v-layout>
    <!-- 图表 -->
    <v-layout>
      <v-flex class="vflex" xs12>
        <v-card class="vcard">
          <el-radio-group
            class="contrast-group"
            v-model="contrastGroup"
            @change="changeContrast"
          >
            <el-radio :label="0">{{
              $t("assessment.PatentsHistoryNumber")
            }}</el-radio>
            <el-radio :label="1">{{ $t("assessment.PatentValue") }}</el-radio>
          </el-radio-group>
          <div id="chartComparisonOne"></div>
        </v-card>
      </v-flex>
    </v-layout>
  </div>
</template>

<script>
import axios from "axios";
import Ecolors from "@/utils/chartsColors.js";
let typesH = null;
export default {
  props: ["propCompanyName"],
  data() {
    return {
      companyName: this.$cookie.get("companyName") || "",
      searchText: this.$route.query.compareName || "",
      cityOptions: [], // 搜索历史
      activeItem: "", // 搜索历史当前选中的公司
      chartComparisonOne: "",
      curCompanyData: [],
      pkCompanyData: [],
      // 图表3需要组装的数据
      chart3Data: {
        name: [],
      },
      curChart3DataData: [],
      pkChart3DataData: [],
      contrastGroup: 0,
      cancel2: null,
    };
  },
  methods: {
    init() {
      this.$get(this.$Url.comparison.companyPk, {
        companyName: this.companyName,
        dataType: "companyPk",
      })
        .then((data) => {
          this.curCompanyData = data;
          this.initData();
          this.renderChart3();
        })
        .catch((err) => {});
    },
    initData() {
      let curData = this.curCompanyData.data || [];
      let pkData = this.pkCompanyData.data || [];
      //
      let curChart3DataName = [];
      let curChart3DataData = [];
      let pkChart3DataName = [];
      let pkChart3DataData = [];
      // 一种是init方法传进来的数据，另一种是search方法传进来的数据
      let arr = (curData.companyPk && curData.companyPk.ipcScoreArr) || curData;
      for (let i in arr) {
        let name = arr[i].value;
        // 图表3需要组装的数据
        curChart3DataName.push(name);
        if (this.contrastGroup === 0) {
          // 专利量
          curChart3DataData.push({
            name: name,
            value: arr[i].num,
            itemStyle: {
              color: Ecolors.color[0],
            },
          });
        } else if (this.contrastGroup === 1) {
          // 专利价值
          curChart3DataData.push({
            name: name,
            value: arr[i].score,
            itemStyle: {
              color: Ecolors.color[0],
            },
          });
        }
      }
      if (!!this.pkCompanyData.data) {
        for (let i in pkData.ipcInfo.companyArr) {
          let name = pkData.ipcInfo.companyArr[i].value;
          // 图表3需要组装的数据
          pkChart3DataName.push(name);
          if (this.contrastGroup === 0) {
            pkChart3DataData.push({
              name: name,
              value: pkData.ipcInfo.companyArr[i].num,
              itemStyle: {
                color: Ecolors.color[2],
              },
            });
          } else if (this.contrastGroup === 1) {
            pkChart3DataData.push({
              name: name,
              value: pkData.ipcInfo.companyArr[i].score,
              itemStyle: {
                color: Ecolors.color[2],
              },
            });
          }
        }
        this.chart3Data.name = Array.from(
          new Set([...curChart3DataName, ...pkChart3DataName])
        );
        let chart3Arr1 = [];
        let chart3Arr2 = [];
        for (let i in this.chart3Data.name) {
          //
          let val1 = 0;
          for (let j in curChart3DataData) {
            if (this.chart3Data.name[i] === curChart3DataData[j].name) {
              val1 = curChart3DataData[j].value;
            }
          }
          chart3Arr1.push({
            name: this.chart3Data.name[i],
            value: val1,
            itemStyle: {
              color: Ecolors.color[0],
            },
          });
          //
          let val2 = 0;
          for (let j in pkChart3DataData) {
            if (this.chart3Data.name[i] === pkChart3DataData[j].name) {
              val2 = pkChart3DataData[j].value;
            }
          }
          chart3Arr2.push({
            name: this.chart3Data.name[i],
            value: val2,
            itemStyle: {
              color: Ecolors.color[1],
            },
          });
        }
        this.curChart3DataData = chart3Arr1;
        this.pkChart3DataData = chart3Arr2;
      } else {
        // 没有比较公司时
        this.chart3Data.name = curChart3DataName;
        this.curChart3DataData = curChart3DataData;
      }
    },
    initOption() {
      let option = {
        legend: {},
        grid: {
          left: "10%",
          bottom: "35%",
        },
        tooltip: {
          backgroundColor: "#fff",
          extraCssText: "box-shadow: 0 0 3px rgba(0, 0, 0, 0.3);",
        },
        color: Ecolors.color,
        xAxis: [
          {
            type: "category",
            nameTextStyle: {
              color: "#b0bad4",
            },
            axisLine: {
              show: false,
            },
            axisTick: {
              show: false,
            },
            axisLabel: {
              fontFamily: "微软雅黑",
              fontStyle: "normal",
              fontWeight: "normal",
              // interval: 0,
              rotate: 30,
              color: "#7d90ae",
            },
          },
        ],
        yAxis: [
          {
            type: "value",
            name: "专利量",
            nameLocation: "end",
            nameTextStyle: {
              padding: [0, 0, 0, -10],
              color: "#7d90ae",
            },
            axisLine: {
              show: false,
            },
            axisTick: {
              show: false,
            },
            axisLabel: {
              color: "#7d90ae",
            },
            splitLine: {
              lineStyle: {
                color: "#d3dbea",
                type: "dashed",
              },
            },
          },
        ],
        barWidth: 30,
        series: [],
      };
      return option;
    },
    // 技术方向比较
    renderChart3() {
      let ths = this;
      let chart3 = this.$echarts.init(
        document.getElementById("chartComparisonOne")
      );
      chart3.setOption(this.initOption(), true);
      let legendData = []
        .concat({
          name: this.companyName,
          textStyle: {
            color: Ecolors.color[0],
          },
        })
        .concat({
          name: this.pkCompanyData.searchText,
          textStyle: {
            color: Ecolors.color[1],
          },
        });
      let option = {
        legend: {
          data: legendData,
        },
        tooltip: {
          formatter: function(params) {
            let name = ths.contrastGroup === 0 ? "专利数量" : "专利价值";
            let str = `<span style="font-size:12px;color:#7d90ae;">${params.name}</span><br/>
              <span style="font-weight:bold;font-size:12px;color:#545c83;">${name}：<i style="font-style:normal;font-weight:bold;font-size:12px;color:#40a8ff;">${params.data.value}</i></span>`;
            return str;
          },
        },
        xAxis: [
          {
            data: this.chart3Data.name,
          },
        ],
        yAxis: [
          {
            type: "value",
            name: this.contrastGroup === 0 ? "专利量" : "专利价值",
          },
        ],
        series: [],
      };
      if (!!this.pkCompanyData.data) {
        option.series = [
          {
            type: "bar",
            name: this.companyName,
            data: this.curChart3DataData,
          },
          {
            type: "bar",
            name: this.pkCompanyData.searchText,
            data: this.pkChart3DataData,
          },
        ];
      } else {
        option.series = [
          {
            type: "bar",
            name: this.companyName,
            data: this.curChart3DataData,
          },
        ];
      }
      chart3.setOption(option);
      // 图例反选
      chart3.off("legendselectchanged");
      chart3.on("legendselectchanged", (obj) => {
        const { selected, name } = obj;
        if (this.currentLegendName !== name) {
          Object.keys(selected).forEach((key) => {
            selected[key] = key === name ? true : false;
          });
          this.currentLegendName = name;
        } else {
          if (selected[name] === false) {
            Object.keys(selected).forEach((key) => {
              selected[key] = true;
            });
            this.currentLegendName = "";
          }
        }
        option.legend.selected = selected;
        chart3.setOption(option);
      });
    },
    // 查询补全
    querySearchAsync(queryString, cb) {
      if (this.cancel2 !== null) {
        this.cancel2();
      }
      if (this.searchText === "") {
        cb([]);
        return;
      }
      let ths = this;
      this.querySearchList = [];
      this.$get(
        this.$Url.comparison.autoComplete,
        {
          keyWord: queryString || this.searchText,
        },
        new axios.CancelToken(function executor(c) {
          ths.cancel2 = c;
        })
      ).then((res) => {
        let list = res.data ? res.data.result : [];
        list.forEach((v) => {
          this.querySearchList.push({ value: v._source.name });
        });
        cb(this.querySearchList);
      });
    },
    // 搜索
    search() {
      if (this.searchText === "") {
        this.$message.error("请输入企业名关键字");
        return;
      }
      this.$get(this.$Url.comparison.ipcGroup, {
        basicName: this.companyName,
        compareName: this.searchText,
      })
        .then((data) => {
          data.searchText = this.searchText;

          if (data.status === 40401) {
            this.$message.error(data.message);
            return;
          }
          this.curCompanyData.data = data.data.ipcInfo.basicArr;
          this.pkCompanyData = data || [];
          // 添加搜索历史
          this.addHistory(this.searchText);
          this.$router.push({
            name: "technicalComparison",
            query: {
              compareName: this.searchText,
            },
          });

          this.initData();
          this.renderChart3();
        })
        .catch((err) => {});
    },
    handleSelect(item) {
      this.searchText = item.value;
      this.search();
    },
    // 获取搜索历史列表
    getHistoryList() {
      this.$post(this.$Url.comparison.historyList, {
        companyName: this.companyName,
      })
        .then((data) => {
          let dataArr = data.data;
          this.cityOptions = [];
          for (let i = 0; i < dataArr.length; i++) {
            this.cityOptions.push(dataArr[i].historyName);
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 添加搜索历史
    addHistory(search) {
      let searchText = search ? search : this.searchText;
      this.$post(this.$Url.comparison.getPkhistoryAdd, {
        companyName: this.companyName,
        historyName: searchText,
      })
        .then((data) => {
          this.getHistoryList();
        })
        .catch((error) => {
          console.log(error);
        });
    },
    searchHistory(search) {
      this.searchText = this.activeItem = search;
      this.search();
    },
    // 切换专利量/专利价值
    changeContrast() {
      this.initData();
      this.renderChart3();
    },
    // 监听watchCompanyName
    watchCompanyName() {
      this.chartComparisonOne.resize();
      // if(this.propCompanyName!==''){
      //   this.searchText = this.propCompanyName
      //   this.search()
      // }
      this.$Bus.$on("goTechComparison", (data) => {
        this.searchText = data.companyName;
        this.activeItem = "";
        this.search();
      });
    },
    // 监听图表resizew
    watchChartResize() {
      this.$Bus.$on("chartResize", (data) => {
        // if (data.active === 3||data.active === '3') {
        //   // 加个小延迟
        //   setTimeout(() => {
        //     this.chartComparisonOne.resize()
        //   }, 100)
        // }
      });
    },
  },
  watch: {
    "$route.query.compareName"() {
      if (
        this.$route.query.compareName &&
        this.$route.query.compareName !== this.searchText
      ) {
        this.searchText = this.activeItem = this.$route.query.compareName;
        this.search();
      }
    },
    // pkCompanyData() {
    //   this.initData()
    //   this.renderChart3()
    // }
  },
  created() {
    this.getHistoryList();
  },
  mounted() {
    this.chartComparisonOne = this.$echarts.init(
      document.getElementById("chartComparisonOne")
    );

    if (this.$route.query.compareName) {
      this.activeItem = this.$route.query.compareName;
      this.search();
    } else {
      this.init();
    }
    this.watchChartResize();
    this.watchCompanyName();
  },
};
</script>

<style lang="scss" scoped>
.vflex {
  margin-bottom: 20px;
}
.vcard {
  width: 100%;
  height: 100%;
}
.vflex.right {
  margin-right: 15px;
}
.vcard-title {
  position: relative;
  padding-top: 0;
  font-size: 14px;
  font-weight: 600;
  color: $mainColor;
}
.vcard-title i {
  position: absolute;
  top: 50%;
  left: 0;
  width: 5px;
  height: 20px;
  margin-top: -8px;
  background-color: $mainColor;
}
.search-bar {
  width: 100%;
}
.search-history {
  display: flex;
  flex-wrap: wrap;
  padding-left: 0;
  margin-top: 14px;
  margin-bottom: 10px;
  list-style: none;
}
.search-history li {
  padding: 4px 16px;
  margin-right: 14px;
  margin-bottom: 10px;
  border-radius: 14px;
  font-size: 12px;
  color: #7775da;
  background-color: #e7e7fc;
  cursor: pointer;
}
.search-history li:hover {
  color: #fff !important;
  background-color: $mainColor !important;
}
.search-history .active {
  font-weight: 600;
  color: #fff !important;
  background-color: $mainColor !important;
}
.contrast-group {
  margin-top: 30px;
  margin-left: 20px;
}
#chartComparisonOne {
  width: 100%;
  height: 500px;
  margin-top: 20px;
  margin-bottom: 10px;
}
</style>
